package net.url;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class FormPoster
{
	private URL url;
	private QueryString query;
	public FormPoster(URL url)
	{
		if(!url.getProtocol().toLowerCase().startsWith("http"))
		{
			throw new IllegalArgumentException("Posting only works for http URLS");
		}
		this.url = url;
	}
	public void add(String name,String value)
	{
		query.add(name, value);
	}
	public URL getURL()
	{
		return this.url;
	}
	public InputStream post() throws IOException
	{
		URLConnection uc = url.openConnection();
		uc.setDoOutput(true);
		OutputStreamWriter out = new OutputStreamWriter(uc.getOutputStream());
		out.write(query.toString());
		out.write("\r\n");
		out.flush();
		out.close();
		return uc.getInputStream();
	}
	public static void main(String[] args)
	{
		URL url;
		try
		{
			url = new URL("http://www.baidu.com");
			FormPoster poster = new FormPoster(url);
			poster.add("name", "value");
			poster.add("email", "a@q.com");
			InputStream in = poster.post();
			InputStreamReader r = new InputStreamReader(in);
			int c;
			while((c=r.read())!=-1)
			{
				System.out.print((char)c);
			}
			in.close();
			
		}
		catch (MalformedURLException e1)
		{
			e1.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}
